package com.demo.emp.controller;


import com.demo.common.vo.Result;
import com.demo.emp.entity.Dept;
import com.demo.emp.entity.Emp;
import com.demo.emp.mapper.DeptMapper;
import com.demo.emp.service.EmpService;
import com.demo.emp.vo.EmpQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpService empService;


    @GetMapping("")
    public String empList() {
        return "emp/empList";
    }

    @GetMapping("/list")
    @ResponseBody
    public Result<Object> getEmpList(EmpQuery empQuery) {
        List<Emp> empList = empService.getEmpList(empQuery);
        Long empCount = empService.getEmpCount(empQuery);
        return Result.success(empList, empCount) ;
    }

    @PostMapping("")
    @ResponseBody
    public Result<Object> addEmp(Emp emp) {
        empService.addEmp(emp);
        return Result.success("添加成功");
    }

    @GetMapping("/add/ui")
    public String toAddEmp(Model model) {
        List<Dept> deptList = empService.getAllDept();
        model.addAttribute("deptList",deptList);
        return "emp/empAdd";
    }

    @DeleteMapping("/{ids}")
    @ResponseBody
    public Result<Object> deleteEmpByIds(@PathVariable("ids") String ids) {
        empService.deleteEmpByIds(ids);
        return Result.success("删除成功");
    }

    @GetMapping("/{id}")
    public String getEmpById(@PathVariable("id") Integer id, Model model) {
        Emp emp = empService.getEmpById(id); // 根据id查询emp对象
        List<Dept> dept = empService.getAllDept(); // 获取全部部门
        model.addAttribute("emp",emp); // 将emp对象放入model中
        model.addAttribute("deptList",dept); // 将deptList放入model中
        return "emp/Edit";
    }

    @PutMapping("")
    @ResponseBody
    public Result<Object> updateEmp(Emp emp) {
        empService.updateEmp(emp);
        return Result.success("修改信息成功");
    }
}
